#include "bsp_ap3216c.h"
#include "bsp_gpio.h"
#include "bsp_delay.h"
#include "bsp_i2c.h"
#include "stdio.h"


/* 初始化AP3216C */
void i2c_ap3216c_init(void)
{


	/* 1. IO初始化 */
	IOMUXC_SetPinMux(IOMUXC_UART4_TX_DATA_I2C1_SCL, 1);				/* 复用为I2C_SCL, 使能 SION 比特位 */
	IOMUXC_SetPinConfig(IOMUXC_UART4_TX_DATA_I2C1_SCL, 0x70B0);		/* IO特性, 使能开漏模式 */

	IOMUXC_SetPinMux(IOMUXC_UART4_RX_DATA_I2C1_SDA, 1);				/* 复用为I2C_SDL */
	IOMUXC_SetPinConfig(IOMUXC_UART4_RX_DATA_I2C1_SDA, 0x70B0);		/* IO特性，使能开漏模式 */


	//I2C 初始化
	i2c_init(I2C1);


	unsigned char value;

	/* AP3216C初始化 */
	ap3216c_writeonebyte(AP3216C_I2C_ADDR, AP3216C_SYSTEMCFG, 0x4);						/* 软件复位AP3216C */
	delayms(50);

	ap3216c_writeonebyte(AP3216C_I2C_ADDR, AP3216C_SYSTEMCFG, 0x3);						/* AP3216C, IR+PS+ALS */
	value = ap3216c_readonebyte(AP3216C_I2C_ADDR, AP3216C_SYSTEMCFG);
	
	printf("AP3216C config value=%02x\r\n", value);
}


/* AP3216C 读一个字节数据, 返回值读取到寄存器的值 */
unsigned char ap3216c_readonebyte(unsigned char addr, unsigned char reg)
{
	unsigned char value = 0;

	struct i2c_transfer masterXfer;

	masterXfer.slaveAddress = addr;
	masterXfer.direction = kI2C_Read;
	masterXfer.subaddress = reg;
	masterXfer.subaddressSize = 1;
	masterXfer.data = &value;
	masterXfer.dataSize = 1;

	i2c_master_transfer(I2C1, &masterXfer);


	return value;
}

/* AP3216C 写一个字节数据, 返回值错误类型 */
unsigned char ap3216c_writeonebyte(unsigned char addr, unsigned char reg, unsigned char data)
{
	unsigned char ret = 0;

	struct i2c_transfer masterXfer;

	masterXfer.slaveAddress = addr;
	masterXfer.direction = kI2C_Write;
	masterXfer.subaddress = reg;
	masterXfer.subaddressSize = 1;
	masterXfer.data = &data;
	masterXfer.dataSize = 1;

	if(i2c_master_transfer(I2C1, &masterXfer))
	{
		/* 出错 */
		ret = 1;
	}

	return ret;
}


void ap3216c_readdata(unsigned short *ir, unsigned short *ps,
	unsigned short *als)
{
	uint8_t buf[6];
	int i = 0;

	for(i=0; i<6; i++){
		buf[i] = ap3216c_readonebyte(AP3216C_I2C_ADDR, AP3216C_IRDATALOW + i);
	}

	//ir 
	if(buf[0] & 0x80){
		//IR和PS无效表示无效
		*ir = 0;
		*ps = 0;
	}
	else{
		*ir = (((unsigned short)buf[1]) << 2) |  (buf[0] & 0x03);
		*ps = (((unsigned short)(buf[5] & 0x3f)) << 4)|  (buf[4] & 0x0f);
		*als = (((unsigned short)buf[3]) << 8) | buf[2];
	}

}